import {login} from '@/api/app'
import {ElNotification} from "element-plus";
import router from "@/router";
import {APP_NAME, COLLAPSE_ENUM, COLLAPSE_KEY, getCollapseValue} from "@/constant";
import {getUnReadCount} from '@/api/im'
import IM from '@/ws/index'

function getUserInfoCache() {
    const v = window.localStorage.getItem('admin_user')
    let value = {}
    try {
        value = JSON.parse(v)
    } catch (e) {
        return {}
    }
    return value
}

function getCollapseCache() {
    const value = window.localStorage.getItem(COLLAPSE_KEY)
    return value === COLLAPSE_ENUM.OPEN
}

function getCurrentHour() {
    const date = new Date()
    return date.getHours()
}

export default {
    namespaced: true,
    state: () => ({
        isCollapse: getCollapseCache(),
        tagList: new Map(),
        userInfo: getUserInfoCache(),
        appName: APP_NAME,
        currentHour: getCurrentHour(),
        bindWs: false,
        unReadCount: 0,
    }),
    actions: {
        async initUnReadCount({commit}) {
            const resp = await getUnReadCount()
            const {data, code} = resp
            if (code !== 1) return
            const {total_num} = data
            commit('setUnReadCount', total_num)
            console.log(resp, 'unreadCount')
        },
        logout({commit}, showMsg = true) {
            IM.logout()
            commit('logout')
            if (!showMsg) return
            ElNotification({
                title: 'Success',
                message: '退出成功!',
                type: 'success',
                duration: 1500,
                onClose: () => {
                    router.replace('/login').catch(null)
                }
            })
        },
        login({commit}, data) {
            return new Promise(resolve => {
                login(data).then(resp => {
                    const {data: {userinfo}} = resp
                    commit('setUserInfo', userinfo)
                    commit('updateHour')
                    resolve([null, userinfo])
                }).catch(err => {
                    resolve([err, null])
                })
            })
        },
    },
    mutations: {
        setUnReadCount(state, value) {
            if (value <= 0) value = 0
            state.unReadCount = value
        },
        changeBindStatus(state, v) {
            state.bindWs = v
        },
        updateHour(state) {
            state.currentHour = getCurrentHour()
        },
        logout(state) {
            state.userInfo = {}
            window.localStorage.removeItem('admin_user')
        },
        setUserInfo(state, data) {
            state.userInfo = data
            if (typeof data === 'object') {
                window.localStorage.setItem('admin_user', JSON.stringify(data))
            }
        },
        changeCollapse(state) {
            const value = !state.isCollapse
            state.isCollapse = value
            window.localStorage.setItem(COLLAPSE_KEY, getCollapseValue(value))
        },
        addTag(state, payload) {
            const {key, value, params, query} = payload
            if (state.tagList.has(key)) return
            state.tagList.set(key, {name: value, params, query})
        },
        deleteTag(state, key) {
            return state.tagList.delete(key)
        }
    }
}
